<template>
  <Codemirror
    v-model:value="code"
    :options="cmOptions"
    ref="cmRef"
    width="99%"
    @ready="onReady"
    KeepCursorInEnd="true"
  >
  </Codemirror>
  <div style="padding-left: 38px; margin-top: 5px; color: red">
    {{ error }}
  </div>

  <div style="text-align: center; margin-top: 15px">
    <button @click="transformJSON">转为JSON</button>
  </div>

  <div style="padding-left: 38px; margin-top: 15px">
    <textarea id="json-textarea" readonly>{{
      jsonstr
    }}</textarea>
  </div>
</template>

<script>
import { ref } from "vue";
import "codemirror/mode/javascript/javascript.js";
import Codemirror from "codemirror-editor-vue3";
import { trimSpecificChars, isNumeric } from "./utils.js";
export default {
  components: { Codemirror },
  setup() {
    const code = ref("insert into `user` (`name`) values ('张三');");
    const cmRef = ref();
    const cmOptions = {
      mode: "text/javascript",
    };
    const jsonstr = ref();
    const error = ref("");

    const onReady = (cm) => {
      cm.focus();
    };

    // insert into `crm_refund_service_order` (`sn`, `trade_oid`, `trade_sn`, `trade_type`, `type`, `stage`, `source`, `e_tid`, `e_refund_id`, `audit_status`, `customer_id`, `seller_corp_id`, `seller_sob_id`, `seller_order_id`, `seller_order_sn`, `seller_order_dtn`, `seller_main_staff_ids`, `seller_store_id`, `seller_remark`, `buyer_refund_account_number`, `creator_uid`, `service_status`, `exchange_status`, `good_status`, `e_status`, `e_refund_amount`, `refund_amount`, `buyer_remark`, `updated_at`, `created_at`) values ('FWD.112025012100009', '230935', 'JYD.112025011200003', '3', '3', '2', '2', '4200954696382912102', '317660761842910221', '2', '1900059', '11', '11', '150441', 'CO.112025011200001', 'crm_sales_order', '147', '8', '', '-', '1', '4', '0', '3', 'WAIT_BUYER_RETURN_GOODS', '16800', '16800', '协商一致退款', '1737468050', '1737468050');

    const transformJSON = () => {
      const insertStmt = code.value;
      const regex =
        /^\s*INSERT\s+INTO\s+`?\w+`?\s*\(([\s\S]*)?\)\s*values\s*\(([\s\S]*)\)\s*;?\s*$/im;
      const match = insertStmt.match(regex);
      console.log("match", match);
      if (!match || match.length !== 3) {
        error.value =
          "请输入格式为：INSERT INTO table_name (列1, 列2,...) VALUES (值1, 值2,....)";
        code.value = "";
        return;
      }

      const [, columnsStr, valuesStr] = match;
      console.log("valuesStr", valuesStr);

      const columns = columnsStr
        .split(",")
        .map((col) => trimSpecificChars(col.trim(), ["`"]));
      const values = [];
      const valuePattern = /'([^']*)'|"([^"]*)"|([^'",\s]+)/gim;
      let valueMatch;
      while ((valueMatch = valuePattern.exec(valuesStr)) !== null) {
        console.log("valueMatch", valueMatch);
        let matchStr = valueMatch[0];
        let val;
        if (matchStr.slice(0, 1) === "'") {
          val = valueMatch[1];
        } else if (matchStr.slice(0, 1) === '"') {
          val = valueMatch[2];
        } else if (isNumeric(matchStr)) {
          val = Number(matchStr);
        } else if (matchStr === "null") {
          val = null;
        } else if (matchStr === "true" || matchStr === "false") {
          val = matchStr === "true";
        } else {
          val = matchStr;
        }

        values.push(val);
      }

      if (columns.length !== values.length) {
        error.value = "列和值数量不匹配";
        code.value = "";
        console.log(
          "columns.length!== values.length",
          columns.length,
          values.length,
        );
        return;
      }

      error.value = "";

      const jsonDict = {};
      for (let i = 0; i < columns.length; i++) {
        jsonDict[columns[i]] = values[i];
      }
      jsonstr.value = JSON.stringify(jsonDict, null, 2);
      console.log("columns, values", columns, values);
    };

    return {
      code,
      cmRef,
      cmOptions,
      jsonstr,
      onReady,
      transformJSON,
      error,
    };
  },
};
</script>
